<template>
  <div class="score-trend-section card">
    <div class="trend-header">
      <div class="header-content">
        <h4>📊 分数趋势分析</h4>
        <p>各科目分数和总分变化趋势</p>
      </div>
    </div>
    
    <!-- 科目选择器和操作区域 -->
    <div class="controls-section">
      <div class="controls-content">
        <!-- 科目选择器 -->
        <div class="subject-control">
          <div class="control-label">
            <span class="label-text">📚 选择科目</span>
            <span class="label-hint">查看分数变化趋势</span>
          </div>
          
          <el-select
            v-model="selectedSubject"
            @change="handleSubjectChange"
            placeholder="请选择科目"
            class="subject-select-dropdown"
            size="large"
          >
            <el-option
              label="总分"
              value="total"
              class="subject-option"
            >
              <div class="option-content">
                <span class="option-label">📈 总分</span>
                <span class="option-desc">所有科目总分趋势</span>
              </div>
            </el-option>
            <el-option
              v-for="subject in availableSubjects"
              :key="subject.name"
              :label="subject.name"
              :value="subject.name"
              class="subject-option"
            >
              <div class="option-content">
                <span class="option-label">{{ subject.name }}</span>
                <span class="option-desc">满分{{ subject.full }}分</span>
              </div>
            </el-option>
          </el-select>
        </div>

        <!-- 操作按钮 -->
        <div class="action-control">
          <el-button
            type="primary"
            :icon="Download"
            @click="exportScoreData"
            :disabled="!sortedHistory.length"
            class="export-btn"
            size="large"
          >
            导出数据
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 图表容器 -->
    <div class="score-trend-chart">
      <div v-if="!sortedHistory.length" class="empty-state">
        <el-icon class="empty-icon"><DataAnalysis /></el-icon>
        <p class="empty-description">暂无历史数据，请先进行计算</p>
      </div>
      <echart
        v-else
        :option="scoreTrendChartOption"
        :style="{ height: isMobile ? '250px' : '350px' }"
        autoresize
      />
    </div>
  </div>
</template>

<script>
import {use} from 'echarts/core'
import {CanvasRenderer} from 'echarts/renderers'
import {LineChart} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {Download, DataAnalysis} from "@element-plus/icons-vue"
import {ElMessage} from 'element-plus'
import * as XLSX from 'xlsx'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent
])

export default {
  name: 'ScoreTrendChart',
  components: {
    echart: VChart,
    DataAnalysis
  },
  props: {
    history: {
      type: Array,
      default: () => []
    },
    subjects: {
      type: Array,
      default: () => []
    },
    isMobile: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedSubject: 'total'
    }
  },
  computed: {
    Download() {
      return Download
    },
    sortedHistory() {
      return [...this.history].reverse()
    },
    availableSubjects() {
      return this.subjects || []
    },
    scoreTrendChartOption() {
      if (!this.sortedHistory.length) return null
      
      const data = this.getScoreData()
      const maxScore = this.getMaxScore()
      
      return {
        title: {
          text: `${this.selectedSubject}趋势`,
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 16,
            fontWeight: 600,
            color: '#303133'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0]
            const date = new Date(data.name).toLocaleString()
            return `${date}<br/>${this.selectedSubject}：${data.value}分`
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e4e7ed',
          borderWidth: 1,
          textStyle: {
            color: '#303133'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.sortedHistory.map(h => new Date(h.timestamp).toLocaleString()),
          axisLabel: {
            rotate: 45,
            interval: this.calculateInterval(), // 使用动态计算的间隔
            formatter: this.formatDate,
            color: '#606266',
            fontSize: 10,
            showMaxLabel: true, // 始终显示最后一个标签
            showMinLabel: true  // 始终显示第一个标签
          },
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          min: 0,
          max: maxScore,
          axisLabel: {
            formatter: '{value}分',
            color: '#606266'
          },
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [{
          name: this.selectedSubject,
          type: 'line',
          data: data,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: this.getSubjectColor(),
            borderColor: '#fff',
            borderWidth: 2
          },
          lineStyle: {
            color: this.getSubjectColor(),
            width: 3
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [{
                offset: 0, color: this.getSubjectColor(0.3)
              }, {
                offset: 1, color: this.getSubjectColor(0.1)
              }]
            }
          }
        }]
      }
    }
  },
  methods: {
    handleSubjectChange(subject) {
      this.selectedSubject = subject
      this.$emit('subject-change', subject)
    },
    
    // 计算x轴标签间隔
    calculateInterval() {
      const dataLength = this.sortedHistory.length
      if (dataLength <= 10) return 0 // 数据少时显示所有标签
      if (dataLength <= 20) return 1 // 每2个显示1个
      if (dataLength <= 50) return 2 // 每3个显示1个
      if (dataLength <= 100) return 4 // 每5个显示1个
      return Math.floor(dataLength / 20) // 最多显示20个标签
    },

    // 格式化日期显示
    formatDate(value) {
      const date = new Date(value);
      const now = new Date();

      const diffMs = now - date; // 毫秒差
      const diffSeconds = Math.floor(diffMs / 1000);
      const diffMinutes = Math.floor(diffSeconds / 60);
      const diffHours = Math.floor(diffMinutes / 60);

      // 把时间部分清零，只比较日期（年月日）
      const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      const diffDays = Math.floor((startOfToday - startOfDate) / (1000 * 60 * 60 * 24));

      if (diffDays === 0) {
        // 今天，根据小时、分钟判断更精确的时间描述
        if (diffHours > 0) {
          return `${diffHours}小时前`;
        } else if (diffMinutes > 0) {
          return `${diffMinutes}分钟前`;
        } else {
          return '刚刚';
        }
      } else if (diffDays === 1) {
        return '昨天';
      } else if (diffDays <= 7) {
        return `${diffDays}天前`;
      } else if (diffDays <= 30) {
        const weeks = Math.floor(diffDays / 7);
        return `${weeks}周前`;
      } else {
        // 超过30天显示具体日期，格式 yyyy-MM-dd
        return date.toLocaleDateString();
      }
    },
    getScoreData() {
      return this.sortedHistory.map(record => {
        if (this.selectedSubject === 'total') {
          return record.total
        } else {
          // 从学生数据中获取对应科目的分数
          const studentData = record.studentDto
          if (studentData && studentData.scores) {
            return studentData.scores[this.selectedSubject] || 0
          }
          return 0
        }
      })
    },
    getMaxScore() {
      if (this.selectedSubject === 'total') {
        // 总分的最大值
        const maxTotal = Math.max(...this.sortedHistory.map(record => record.total))
        return Math.ceil(maxTotal * 1.1) // 增加10%的余量
      } else {
        // 找到对应科目的满分
        const subject = this.availableSubjects.find(s => s.name === this.selectedSubject)
        return subject ? subject.full : 100
      }
    },
    getSubjectColor(alpha = 1) {
      const colors = {
        'total': '#67C23A',
        '语文': '#409EFF',
        '数学': '#E6A23C',
        '英语': '#F56C6C',
        '物理': '#909399',
        '化学': '#9C27B0',
        '生物': '#4CAF50'
      }
      
      const baseColor = colors[this.selectedSubject] || '#409EFF'
      if (alpha === 1) return baseColor
      
      // 转换为rgba格式
      const hex = baseColor.replace('#', '')
      const r = parseInt(hex.substr(0, 2), 16)
      const g = parseInt(hex.substr(2, 2), 16)
      const b = parseInt(hex.substr(4, 2), 16)
      return `rgba(${r}, ${g}, ${b}, ${alpha})`
    },
    exportScoreData() {
      if (!this.sortedHistory.length) {
        ElMessage.warning('暂无数据可导出')
        return
      }

      // 准备导出数据
      const exportData = this.sortedHistory.map(record => {
        const baseData = {
          '时间': new Date(record.timestamp).toLocaleString(),
          '总分': record.total
        }

        // 添加各科目分数
        if (record.studentDto && record.studentDto.scores) {
          this.availableSubjects.forEach(subject => {
            baseData[subject.name] = record.studentDto.scores[subject.name] || 0
          })
        }

        return baseData
      })

      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(exportData, {
        header: Object.keys(exportData[0])
      })

      // 设置列宽
      const colWidths = [
        {wch: 20}, // 时间
        {wch: 10}, // 总分
        ...this.availableSubjects.map(() => ({wch: 10})) // 各科目
      ]
      ws['!cols'] = colWidths

      XLSX.utils.book_append_sheet(wb, ws, '分数趋势数据')
      XLSX.writeFile(wb, `分数趋势数据_${new Date().toLocaleDateString()}.xlsx`)
      
      ElMessage.success('分数趋势数据导出成功')
    }
  }
}
</script>

<style scoped>
/* 分数趋势区域 */
.score-trend-section {
  padding: var(--spacing-lg);
  transition: var(--transition-base);
}

.score-trend-section:hover {
  transform: translateY(-2px);
}

.trend-header {
  margin-bottom: var(--spacing-lg);
  text-align: center;
}

.header-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-xs);
}

.trend-header h4 {
  margin: 0;
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
}

.trend-header p {
  margin: 0;
  color: var(--text-light);
  font-size: var(--font-size-base);
}

/* 控制区域 */
.controls-section {
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-lg);
  background: var(--gradient-glass);
  border-radius: var(--border-radius-small);
  border: 1px solid rgba(255, 255, 255, 0.4);
  transition: var(--transition-base);
  backdrop-filter: blur(10px);
}

.controls-section:hover {
  background: var(--gradient-glass-heavy);
  transform: translateY(-1px);
  box-shadow: var(--shadow-light);
}

.controls-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  gap: var(--spacing-lg);
  flex-wrap: wrap;
}

/* 科目控制 */
.subject-control {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  flex: 1;
  min-width: 250px;
}

.control-label {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.label-text {
  font-size: var(--font-size-base);
  font-weight: 600;
  color: var(--text-primary);
}

.label-hint {
  font-size: var(--font-size-sm);
  color: var(--text-light);
  font-style: italic;
}

/* 操作控制 */
.action-control {
  display: flex;
  align-items: flex-end;
}

.export-btn {
  border-radius: var(--border-radius-small);
  font-weight: 500;
  transition: var(--transition-base);
  min-width: 120px;
  background: var(--gradient-primary);
  border: none;
  box-shadow: var(--shadow-light);
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-medium);
  background: var(--gradient-primary-reverse);
}

.export-btn:disabled {
  background: var(--text-light);
  transform: none;
  box-shadow: none;
}

/* 科目选择下拉框 */
.subject-select-dropdown {
  width: 100%;
  max-width: 300px;
}

.subject-select-dropdown :deep(.el-input__wrapper) {
  border-radius: var(--border-radius-small);
  transition: var(--transition-fast);
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: var(--shadow-light);
}

.subject-select-dropdown :deep(.el-input__wrapper:hover) {
  box-shadow: var(--shadow-medium);
  transform: translateY(-1px);
  border-color: var(--primary-color);
}

.subject-select-dropdown :deep(.el-input__wrapper.is-focus) {
  box-shadow: var(--shadow-medium);
  border-color: var(--primary-color);
  transform: translateY(-1px);
}

.subject-select-dropdown :deep(.el-input__inner) {
  font-size: var(--font-size-base);
  font-weight: 500;
  color: var(--text-primary);
}

.subject-option {
  padding: var(--spacing-sm) var(--spacing-md);
  transition: var(--transition-fast);
}

.subject-option:hover {
  background: rgba(64, 158, 255, 0.1);
}

.option-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.option-label {
  font-weight: 600;
  color: var(--text-primary);
  font-size: var(--font-size-base);
}

.option-desc {
  font-size: var(--font-size-sm);
  color: var(--text-light);
  opacity: 0.8;
}

/* 图表容器 */
.score-trend-chart {
  background: var(--gradient-glass-heavy-2);
  border-radius: var(--border-radius-small);
  padding: var(--spacing-lg);
  box-shadow: var(--shadow-light);
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(255, 255, 255, 0.4);
  transition: var(--transition-base);
  backdrop-filter: blur(10px);
}

.score-trend-chart:hover {
  box-shadow: var(--shadow-medium);
  transform: translateY(-1px);
}

/* 空状态样式由全局 components.css 提供 */

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .score-trend-section {
    padding: var(--spacing-md);
  }
  
  .controls-section {
    padding: var(--spacing-md);
  }
  
  .controls-content {
    flex-direction: column;
    align-items: stretch;
    gap: var(--spacing-md);
  }
  
  .subject-control {
    min-width: auto;
  }
  
  .action-control {
    align-items: center;
  }
  
  .export-btn {
    width: 100%;
  }
  
  .subject-select-dropdown {
    max-width: none;
  }
  
  .score-trend-chart {
    padding: var(--spacing-md);
  }
}

@media screen and (max-width: 480px) {
  .score-trend-section {
    padding: var(--spacing-sm);
  }
  
  .controls-section {
    padding: var(--spacing-sm);
  }
  
  .score-trend-chart {
    padding: var(--spacing-sm);
  }
  
  .empty-state {
    padding: var(--spacing-lg);
  }
}
</style> 